<template>
	<view v-if="visible" :class="['popup-wrap']" @touchmove.stop.prevent>
		<view class="popup-mask" @tap.stop="close">
			<view :class="['popup-panel', 'fade-in']" @tap.stop>
				<cc-navigate-bar title="预约时间">
					<template #right>
						<view @tap="close" class="close-btn"><text class="iconfont">&#xe68c;</text></view>
					</template>
				</cc-navigate-bar>
				<view class="content">
					<scroll-view class="left" :scroll-y="true">
						<view v-for="(date, index) in dateList" :class="['item', index==currentDateIndex? 'active':'' ]"
							@tap="toggleDate(date, index)" :key="index">
							<text v-if="isCurrentDay(date)" class="today-tag">今天</text>
							<text v-else-if="isNextDay(date)" class="tomorrow-tag">明天</text>
							<text v-else>{{ date.format('M-D') }}</text>
						</view>
					</scroll-view>
					<scroll-view class="right" scroll-y :scroll-top="scrollTop">
						<view v-for="(time, index) in timeOptions"
							:class="['item', index==currentTimeIndex? 'active':'' ]" :key="index"
							@tap="chooseTime(time, index)">
							<veiw><text>{{ time.label }}</text></veiw>
							<veiw v-if="index==currentTimeIndex"><cc-form-checkbox shape="circle" :checked="true"
									primaryColor="#000" /></veiw>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import dayjs from 'dayjs'
	export default {
		name: "cc-schedule-time",
		props: {
			// 时间间隔（分钟）
			interval: {
				type: Number,
				default: 30
			},
		},
		data() {
			return {
				visible: false,
				scrollTop: 0,
				selectedTime: null,
				dateList: [],
				timeOptions: [],
				currentDateIndex: 0,
				currentTimeIndex: 0,
				begin: '09:00',
				end: '23:00',
			}
		},
		watch: {			
		},
		methods: {
			/**
			 * 打开弹窗
			 */
			open() {
				this.visible = true;
				this.generateDateList(this.begin, this.end)
				let date = this.dateList[0];
				this.generateTimeOptions(date, this.begin, this.end)
			},
			/**
			 * 关闭弹窗
			 */
			close() {
				this.visible = false;
			},

			/**
			 * 时间切换回顶
			 */
			goTop() {
				this.$nextTick(function() {
					this.scrollTop = 0;
				});
			},

			/**
			 * 切换日期
			 * @param {Object} date
			 */
			toggleDate(date, index) {
				this.currentDateIndex = index;
				this.generateTimeOptions(date, this.begin, this.end);
			},

			chooseTime(time, index) {
				this.currentTimeIndex = index;
				this.$emit("change", time);
				setTimeout(() => {
					this.close();
				}, 100);
			},

			/**
			 * 生成日期列表（当天+次日）
			 * @param {Object} beginTime
			 * @param {Object} endTime
			 */
			generateDateList(beginTime, endTime) {
				const today = dayjs().startOf('day')
				const now = dayjs()
				let opening = this.openingHours(today, beginTime, endTime);

				// 比较当前时间是否在营业时间后		
				if (opening.end.isBefore(now)) {
					this.dateList = [
						today.add(1, 'day')
					]
				} else {
					this.dateList = [
						today,
						today.add(1, 'day')
					]
				}
			},

			/**
			 * 生成时间列表
			 * @param {Object} day 日期
			 * @param {Object} beginTime 开始日期
			 * @param {Object} endTime 结始日期
			 */
			generateTimeOptions(day, beginTime, endTime) {
				this.timeOptions = []
				let opening = this.openingHours(day, beginTime, endTime);

				let begin = opening.begin;
				let end = opening.end;

				const now = dayjs();
				// 传入的日期是否当天	
				// type 类型 1为现在（立即配送/立即取餐）
				// type 类型 2为预约
				// 秒级时间戳（10位）用于标记选取时的时间戳和提交订单时的时间戳比较
				if (this.isCurrentDay(day) && opening.begin.isBefore(now)) {
					begin = now;
					this.timeOptions.push({
						value: begin,
						label: '现在',
						type: 1,
						unixTimestamp: dayjs().unix(),
					})
				} else {
					this.timeOptions.push({
						value: begin,
						label: this.formatTime(begin),
						type: 2,
						unixTimestamp: dayjs().unix(),
					})
				}

				let roundMinute = Math.round(begin.minute() / 10) * 10;

				// 生成时间选项
				let current = begin.set('minute', roundMinute);
				current = current.add(this.interval, 'minute');

				while (current.isBefore(end)) {
					this.timeOptions.push({
						value: current,
						label: this.formatTime(current),
						type: 2,
						unixTimestamp: dayjs().unix(),
					})
					current = current.add(this.interval, 'minute')
				}
			},

			/**
			 * 带日期的营业时间
			 * @param {Object} beginTime
			 * @param {Object} endTime
			 */
			openingHours(day, beginTime, endTime) {
				// 默认开始时间和结束时间
				let beginHour = parseInt(beginTime.slice(0, 2))
				let beginMinute = parseInt(beginTime.slice(3, 5))
				let begin = day.set('hour', beginHour).set('minute', beginMinute)

				let endHour = parseInt(endTime.slice(0, 2))
				let endMinute = parseInt(endTime.slice(3, 5))
				let end = day.set('hour', endHour).set('minute', endMinute)

				return {
					begin: begin,
					end: end,
				}
			},


			// 格式化时间显示
			formatTime(time) {
				return time.format('HH:mm')
			},

			// 判断是否是当天
			isCurrentDay(date) {
				return date.isSame(dayjs(), 'day')
			},

			// 判断是否是次日
			isNextDay(date) {
				return date.isSame(dayjs().add(1, 'day'), 'day')
			}
		}
	}
</script>

<style scoped lang="scss">
	@import "@/cc-ui-tools/scss/theme.scss";
	@import "@/cc-ui-tools/scss/animation.scss";

	.popup-wrap {
		position: fixed;
		min-height: 100vh;
		right: 0;
		left: 0;
		bottom: 0;
		z-index: 999;

		.popup-mask {
			position: relative;
			background: rgba(0, 0, 0, 0.5);
			min-height: 100vh;
			width: 100%;
		}

		.popup-panel {
			position: absolute;
			left: 0;
			right: 0;
			bottom: 0;
			height: 500rpx;
			background: #fff;
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;

			&.fade-in {
				animation: fadeInUp 0.3s 0s linear both;
			}

			&.fade-out {
				animation: fadeOutDown 0.3s 0s linear both;
			}

			.content {
				padding: 0 20rpx;
				display: flex;
				height: calc(100% - 88rpx);
				gap: 30rpx;

				.left {
					width: 22vw;
					overflow: hidden;

					.item {
						padding: 40rpx 10rpx;
						font-size: 26rpx;
						color: #666;
						text-align: center;
						border-right: 2rpx solid transparent;
						transition: all 0.3s;

						&.active {
							color: #000;
							background: #f8f8f8;
							font-weight: 600;
							border-right: 2rpx solid #000;
						}
					}
				}

				.right {
					flex: 1;
					overflow: hidden;

					.item {
						padding: 20rpx 50rpx;
						display: flex;
						justify-content: space-between;

						&.active {
							color: #000;
							font-weight: 600;
						}
					}
				}
			}

			.close-btn {
				display: flex;
				justify-content: flex-end;
				padding-right: 30rpx;
			}
		}
	}
</style>